# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : Notice.py
# Time       ：2023/12/17 16:32
# Author     ：Y-aong
# version    ：python 3.10
# Description：消息通知
"""
import smtplib
from datetime import datetime
from email.mime.text import MIMEText

from pydantic import Field

from conf.config import OrderLinesConfig, EmailConfig
from orderlines.libraries.BaseTask import BaseTask
from orderlines.utils.base_orderlines_type import BasePluginParam
from orderlines.utils.orderlines_enum import TaskStates
from orderlines.utils.utils import get_task_instance
from public.logger import logger


class Email(BasePluginParam):
    msg: str = Field(description='发送消息')
    receivers: str = Field(description='邮件接收者')


class Notice(BaseTask):
    version = OrderLinesConfig.version
    title = '消息通知'
    category = '内置功能'
    icon = 'Tools'

    def __init__(self):
        super(Notice, self).__init__()
        self.mail_host = EmailConfig.mail_host
        self.mail_user = EmailConfig.mail_user
        self.mail_pwd = EmailConfig.mail_pwd
        self.sender = EmailConfig.sender

    @staticmethod
    def _get_task_info(task_instance_id: str):
        from apis.orderlines.models import Process
        from apis.orderlines.schema.process_schema import ProcessSchema
        from public.base_model import session_scope
        with session_scope() as session:
            task_info = get_task_instance(task_instance_id)
            process_id = task_info.get('process_id')
            process_obj = session.query(Process).filter(Process.process_id == process_id).first()
            process_info = ProcessSchema().dump(process_obj)
            return task_info.get('task_name'), process_info.get('process_name')

    def _build_email_msg(
            self,
            task_instance_id: str,
            message=None,
    ) -> tuple:
        """构建发送邮件消息。Build mail message"""
        task_name, process_name = self._get_task_info(task_instance_id)
        title = f'流程名称:{process_name},任务名称:{task_name}——邮件发送'
        msg = f'流程名称:{process_name} \n' \
              f'任务名称:{task_name} \n' \
              f'发送时间:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")} \n' \
              f'邮件内容:{message}'

        return title, msg

    def send_email(self, email_info: Email):
        """
        邮件通知
        @return:
        """
        title, msg = self._build_email_msg(email_info.task_instance_id, email_info.msg)
        message = MIMEText(msg, 'plain', 'utf-8')
        message['Subject'] = title
        message['From'] = self.sender
        message['To'] = email_info.receivers
        smtp_obj = smtplib.SMTP()
        smtp_obj.connect(self.mail_host, 25)
        smtp_obj.login(self.mail_user, self.mail_pwd)
        smtp_obj.sendmail(self.sender, email_info.receivers, message.as_string())
        smtp_obj.quit()
        logger.info('邮件发送成功！')
        return {'status': TaskStates.green.value}
